package initialize

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_translations "github.com/go-playground/validator/v10/translations/en"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"mxshop_api/user-web/global"
	"reflect"
	"strings"
)

func InitTrans(local string)(err error){
	if v,ok :=binding.Validator.Engine().(*validator.Validate); ok{
		//注册一个json的tag自定义方法
		v.RegisterTagNameFunc(func(fld reflect.StructField)string{
			name :=strings.SplitN(fld.Tag.Get("json"),",",2)[0]
			if name =="-"{
				return ""
			}
			return name
		})
		//注册一个json的tag自定义方法
		zhT :=zh.New()
		enT :=en.New()
		uni :=ut.New(enT,zhT,enT)
		global.Trans ,ok =uni.GetTranslator(local)
		if !ok{
			return fmt.Errorf("uni.GetTranslator(%s)",local)
		}
		switch local {
		case "en":
			en_translations.RegisterDefaultTranslations(v,global.Trans)
		case "zh":
			zh_translations.RegisterDefaultTranslations(v,global.Trans)
		default:
			en_translations.RegisterDefaultTranslations(v,global.Trans)
		}
		return
	}
	return
}